<template>
  <div class="ry-input-number">
    <a-tooltip :title="num">
      <a-input class="ry-input-number-container" v-bind="attrs" v-model="num" @change="onchange"
        @blur="onblur">
        <a class="ry-input-number-btn" slot="addonBefore" @click="reduce">-</a>
        <a class="ry-input-number-btn" slot="addonAfter" @click="add">+</a>
      </a-input>
    </a-tooltip>
  </div>
</template>
<script>
export default {
  components: {},
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      default: ''
    },
    min: {
      type: Number,
      default: -Infinity
    },
    max: {
      type: Number,
      default: Infinity
    },
    step: {
      type: Number,
      default: 1
    },
    precision: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      num: 0,
      settings: {
      },
      methods: {
      }
    }
  },
  watch: {
    value: {
      handler (newVal, oldVal) {
        this.num = newVal
      },
      immediate: true
    }
  },
  computed: {
    attrs () {
      return Object.assign({}, { ...this.settings }, this.$attrs)
    },
    listeners () {
      return Object.assign({}, { ...this.methods }, this.$listeners)
    }
  },
  mounted () {
  },
  methods: {
    // 加
    add () {
      this.num = +this.num + this.step
      this.num = Number(this.num.toFixed(this.precision))
      if (this.num <= this.min) {
        this.num = this.min
      }
      if (this.num >= this.max) {
        this.num = this.max
      }
      this.$emit('change', this.num)
    },
    // 减
    reduce () {
      this.num = +this.num - this.step
      this.num = Number(this.num.toFixed(this.precision))
      if (this.num <= this.min) {
        this.num = this.min
      }
      if (this.num >= this.max) {
        this.num = this.max
      }
      this.$emit('change', this.num)
    },
    onchange (e) {
      this.$emit('change', e.target.value)
    },
    onblur (e) {
      let value = Number(e.target.value)

      if (isNaN(value) || Math.abs(value) >= Infinity) {
        this.$emit('change', '')
        return
      }
      if (value <= this.min) {
        this.num = this.min
      }
      if (value >= this.max) {
        this.num = this.max
      }
      this.$emit('change', this.num)
    }
  }
}
</script>
<style lang="less">
.ry-input-number {
  .ry-input-number-container {
    width: 110px;
  }
  .ant-input {
    padding: 4px;
    text-align: center;
    width: 100%;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .ant-input-group-addon {
    background: fade(@btn-default-bg, 40%);
    .ry-input-number-btn {
      font-weight: bold;
      color: @text-color;
    }
  }
}
</style>
